import datetime
import logging
import os.path
from configparser import ConfigParser

from src64.serial_port_py import SerialPort
from src64 import upload_report as upload
from src64.main_entry import MainEntry

"""
    端口监听,键盘监听,报告上传等服务
"""


def set_log():
    """
    设置日志格式
    :return:
    """
    dir = 'logs'
    if not os.path.exists(dir):
        os.mkdir(dir)
    logging.basicConfig(filename=f'{dir}\\{datetime.date.today()}.txt',
                        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s-%(funcName)s',
                        level=logging.INFO)

    logger = logging.getLogger('main')
    fh = logging.FileHandler('log.txt')
    fh.setLevel(logging.DEBUG)
    fh.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s-%(funcName)s'))

    # 使用StreamHandler输出到屏幕
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    ch.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s-%(funcName)s'))

    # 添加两个Handler
    logger.addHandler(ch)
    logger.addHandler(fh)


if __name__ == '__main__':
    # 读取配置文件中的配置信息
    conf = ConfigParser()
    conf.read('./conf.ini', encoding='utf-8-sig')
    if conf.has_option(section='base', option='log') and conf['base']['log'] == '1':
        set_log()

    report = upload.Report(conf) if conf['service']['open_report_upload'] == '1' else None
    if report:
        report.start()

    serialPort = SerialPort(conf) if (conf['service']['open_serial_port'] == '1' or conf['service']['open_keyboard'] == '1') else None
    print("serialPort:",serialPort)
    if serialPort:
        serialPort.start()
    mainEntry = MainEntry(report=report, serial_port=serialPort, conf=conf)
    mainEntry.start()
